package com.example.order.fragment;

import android.app.AlertDialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.Spinner;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.Target;
import com.example.order.R;
import com.example.order.pojo.Dish;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class ConsumerOrderFoodFragment extends Fragment {
    TextView titleTextView;
    ListView dishListView;
    Button orderDishButton, deleteButton, refreshButton;

    // 声明成员变量
    private String consumer_id;

    private static final String BASE_URL = "http://10.2.0.232:8080/backend-api-endpoint";

    public ConsumerOrderFoodFragment() {
        // 必需的空构造函数
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // 为此片段膨胀布局
        View view = inflater.inflate(R.layout.fragment_consumer_order_food, container, false);

        // 获取对 UI 元素的引用
        titleTextView = view.findViewById(R.id.titleTextView);
        dishListView = view.findViewById(R.id.dishListView);
        refreshButton = view.findViewById(R.id.refreshButton);

        // 设置 ListView 选择模式
        dishListView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);

        refreshButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getAllDishs();
            }
        });

        // 在片段创建时调用方法以获取所有菜品
        getAllDishs();

        return view;
    }

    // 将日期时间格式化为字符串
    public static String formatDateTime(Date dateTime) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
        return sdf.format(dateTime);
    }

    // 将字符串解析为日期时间
    public static Date parseDateTime(String dateTimeString) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
        return sdf.parse(dateTimeString);
    }

    private void orderDish(Dish dish) {
        // 显示带有输入的自定义布局的 AlertDialog
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        View dialogView = LayoutInflater.from(getContext()).inflate(R.layout.dialog_order_dish, null);
        builder.setView(dialogView);

        ImageView dishImageView = dialogView.findViewById(R.id.dishImageView);
        TextView dishNameTextView = dialogView.findViewById(R.id.dishNameTextView);
        TextView dishPriceTextView = dialogView.findViewById(R.id.dishPriceTextView);
        EditText quantityEditText = dialogView.findViewById(R.id.quantityEditText);
        Spinner timeSpinner = dialogView.findViewById(R.id.timeSpinner);
        Button submitOrderButton = dialogView.findViewById(R.id.submitOrderButton);

        // 在弹出的对话框中设置当前菜品的信息
        Glide.with(getContext())
                .load("http://10.2.0.232:8080/dish_img/" + dish.getImg())
                .apply(new RequestOptions()
                        .override(400, 400)
                        .centerCrop()
                )
                .listener(new RequestListener<Drawable>() {
                    @Override
                    public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) {
                        Log.e("GlideDebug", "Failed to load image: " + e.getMessage(), e);
                        return false;
                    }

                    @Override
                    public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
                        Log.d("GlideDebug", "Image loaded successfully");
                        return false;
                    }
                })
                .into(dishImageView);

        dishNameTextView.setText("菜品名: " + dish.getDish_name());
        dishPriceTextView.setText("价格: " + dish.getPrice());

        // TODO: 设置 Spinner 的适配器和选项
        // 设置 Spinner 的适配器和选项（例子）
        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(getContext(),
                R.array.time_options, android.R.layout.simple_spinner_item);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        timeSpinner.setAdapter(adapter);

        AlertDialog dialog = builder.create();
        dialog.show();




        submitOrderButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 获取数量
                String quantityString = quantityEditText.getText().toString().trim();

                // 检查数量是否为空
                if (quantityString.isEmpty()) {
                    // 提示用户数量不能为空
                    Toast.makeText(getContext(), "数量不能为空", Toast.LENGTH_SHORT).show();
                    return;
                }

                int quantity = Integer.parseInt(quantityString);

                // 获取 Spinner 的选中项（例子）
                String selectedTime = String.valueOf(timeSpinner.getSelectedItem());

                Log.d("OrderDish", "Dish ID: " + dish.getDish_id() + ", Window ID: " + dish.getWindow_id());
                Log.d("OrderDish", "Quantity: " + quantity + ", Selected Time: " + selectedTime);
                String price = dish.getPrice();

                double total = Double.parseDouble(price) * quantity;



                // 获取当前日期和时间
                Calendar calendar = Calendar.getInstance();
                Date currentTime = calendar.getTime();

                // 使用 formatDateTime 方法将当前时间格式化为字符串
                String formattedCurrentTime = formatDateTime(currentTime);

                // 将用户选择的时间添加到当前日期
                String combinedTime = combineDateTime(formattedCurrentTime, selectedTime);

                // 构建订单 JSON 数据
                JSONObject orderJson = new JSONObject();
                try {
                    orderJson.put("dishId", dish.getDish_id());
                    orderJson.put("window_id", dish.getWindow_id());
                    // 在onCreateView或其他适当的方法中
                    Bundle args = getArguments();
                    if (args != null) {
                        consumer_id = args.getString("consumer_id", "");
                        orderJson.put("consumer_id", consumer_id);
                    }
                    orderJson.put("dish_name", dish.getDish_name());
                    orderJson.put("quantity", quantity);
                    orderJson.put("total", total);
                    orderJson.put("pickup_time", combinedTime);  // 使用拼接后的时间
                } catch (JSONException e) {
                    e.printStackTrace();
                }



                // 构建 OkHttp 请求
                OkHttpClient client = new OkHttpClient();
                String url = BASE_URL + "/placeOrder";
                RequestBody requestBody = RequestBody.create(orderJson.toString(), MediaType.get("application/json"));
                Request request = new Request.Builder()
                        .url(url)
                        .post(requestBody)
                        .build();

                // 发起异步请求
                client.newCall(request).enqueue(new okhttp3.Callback() {
                    @Override
                    public void onResponse(okhttp3.Call call, Response response) throws IOException {
                        if (response.isSuccessful()) {
                            // 订单成功，处理响应
                            final String message = response.body().string();
                            Log.d("OrderDebug+++++", "Response: " + message);
                            getActivity().runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    Toast.makeText(getContext(), message, Toast.LENGTH_SHORT).show();
                                    // 刷新菜品列表
                                    getAllDishs();
                                }
                            });
                        } else {
                            // 订单失败，处理错误响应
                            getActivity().runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    Toast.makeText(getContext(), "Failed to place order", Toast.LENGTH_SHORT).show();
                                }
                            });
                        }
                        // 关闭 AlertDialog
                        dialog.dismiss();
                    }

                    @Override
                    public void onFailure(okhttp3.Call call, IOException e) {
                        // 处理网络请求失败
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(getContext(), "Network error", Toast.LENGTH_SHORT).show();
                            }
                        });
                        // 关闭 AlertDialog
                        dialog.dismiss();
                    }
                });
            }
        });
    }

    // 将日期和时间拼接成一个字符串
    private String combineDateTime(String currentDate, String selectedTime) {

        return currentDate.substring(0, 11) + selectedTime + ":00";
    }
    private class GetAllDishsTask extends AsyncTask<Void, Void, List<Dish>> {
        @Override
        protected List<Dish> doInBackground(Void... voids) {
            OkHttpClient client = new OkHttpClient();
            String url = BASE_URL + "/getAllDishs";

            Request request = new Request.Builder()
                    .url(url)
                    .get()
                    .build();

            try {
                Response response = client.newCall(request).execute();

                if (response.isSuccessful()) {
                    String responseBody = response.body().string();
                    // 解析获取到的菜品列表
                    List<Dish> dishList = parseDishList(responseBody);
                    System.out.println("+++++++++" + dishList.toString());
                    return dishList;
                } else {
                    Log.e("GetAllDishs", "Error: " + response.code());
                    return null;
                }
            } catch (IOException e) {
                e.printStackTrace();
                Log.e("GetAllDishs", "Error: " + e.getMessage());
                return null;
            }
        }

        private class DishAdapter extends ArrayAdapter<Dish> {
            public DishAdapter(Context context, List<Dish> dishs) {
                super(context, R.layout.consumer_list_item_layout, dishs);
            }

            @NonNull
            @Override
            public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
                if (convertView == null) {
                    convertView = LayoutInflater.from(getContext()).inflate(R.layout.consumer_list_item_layout, parent, false);
                }

                Dish dish = getItem(position);

                ImageView imgv = convertView.findViewById(R.id.img);
                TextView text1 = convertView.findViewById(R.id.text1);
                TextView text2 = convertView.findViewById(R.id.text2);
                TextView text3 = convertView.findViewById(R.id.text3);
                TextView text4 = convertView.findViewById(R.id.text4);
                TextView text5 = convertView.findViewById(R.id.text5);
                TextView text6 = convertView.findViewById(R.id.text6);

                if (dish != null && dish.getImg() != null && !dish.getImg().isEmpty()) {
                    String imageUrl = "http://10.2.0.232:8080/dish_img/" + dish.getImg();

                    Glide.with(getContext())
                            .load(imageUrl)
                            .apply(new RequestOptions()
                                    .override(400, 400)
                                    .centerCrop()
                            )
                            .listener(new RequestListener<Drawable>() {
                                @Override
                                public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) {
                                    Log.e("GlideDebug", "Failed to load image: " + e.getMessage(), e);
                                    return false;
                                }

                                @Override
                                public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
                                    Log.d("GlideDebug", "Image loaded successfully");
                                    return false;
                                }
                            })
                            .into(imgv);
                    imgv.setVisibility(View.VISIBLE);
                } else {
                    imgv.setVisibility(View.GONE);
                }

                text1.setText("菜品名: " + dish.getDish_name());
                text2.setText("窗口名: " + dish.getWindow_name());
                text3.setText("价格: " + dish.getPrice());
                text4.setText("窗口id:" + dish.getWindow_id());
                text5.setText("菜单id:" + dish.getMenu_id());

                Button orderDishButton = convertView.findViewById(R.id.orderDishButton);
                orderDishButton.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Dish selectedDish = getItem(position);
                        orderDish(selectedDish);
                    }
                });

                return convertView;
            }
        }

        @Override
        protected void onPostExecute(List<Dish> dishList) {
            if (dishList != null) {
                DishAdapter adapter = new DishAdapter(getActivity(), dishList);
                dishListView.setAdapter(adapter);

                for (Dish dish : dishList) {
                    Log.d("DishInfo", "ID: " + dish.getDish_id() + ", Name: " + dish.getDish_name() + ", Img: " + dish.getImg());
                }
            }
        }
    }

    private List<Dish> parseDishList(String responseBody) {
        List<Dish> dishList = new ArrayList<>();
        try {
            JSONArray jsonArray = new JSONArray(responseBody);
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject jsonDish = jsonArray.getJSONObject(i);
                Dish dish = new Dish();

                dish.setDish_name(jsonDish.getString("dish_name"));
                dish.setWindow_name(jsonDish.getString("window_name"));
                dish.setPrice(jsonDish.getString("price"));
                dish.setDish_id(jsonDish.getString("dish_id"));
                dish.setMenu_id(jsonDish.getString("menu_id"));
                dish.setWindow_id(jsonDish.getString("window_id"));
                dish.setImg(jsonDish.getString("img"));

                dishList.add(dish);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return dishList;
    }

    public void getAllDishs() {
        new GetAllDishsTask().execute();
    }




}
